package com.czx.drivingtest.interceptor;

import com.czx.drivingtest.model.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常拦截器
 * @author czx
 * @version 2020/5/29 11:35 下午
 * @since JDK12
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionInterceptor {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionInterceptor.class);

    @ExceptionHandler(value = Exception.class)
    public ResponseData<Void> exceptionHandler(Exception e) {
        logger.error("捕获到异常", e);
        ResponseData<Void> result = new ResponseData<>();
        result.setCode(-1);
        result.setMsg(e.getMessage());
        return result;
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseData<Void> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        logger.error("捕获到异常", e);
        ResponseData<Void> result = new ResponseData<>();
        result.setCode(-1);
        result.setMsg(e.getBindingResult().getFieldError().getDefaultMessage());
        return result;
    }
}